﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace await
{
    class Program
    {
        static async Task Main(string[] args)
        {
            SendMessage();//如果不加await关键字，该线程还是当前线程
            Console.WriteLine($"Thread 0 is {Thread.CurrentThread.ManagedThreadId}");
            Console.WriteLine("out send message");
            Console.ReadLine();
            /*
             * who will first
             * Thread 1 is ...
             * Thread 0 is ...
             * out send message
             * Thread 2 is ...
             * sending message...
             * Thread 3 is ...
             * Thread 4 is ...
             * Thread 5 is ...
             * end send message
             */
        }

        public async static Task SendMessage()
        {
            Thread.Sleep(1000);
            Console.WriteLine("who will first");
            Console.WriteLine($"Thread 1 is {Thread.CurrentThread.ManagedThreadId}");
            
            //await之后的内容与await里的内容是同一个线程
            await Task.Run(() =>
            {
                Console.WriteLine($"Thread 2 is {Thread.CurrentThread.ManagedThreadId}");
                Thread.Sleep(2000);
                Console.WriteLine("sending message");
            });

           
            Thread.Sleep(1000);
            Console.WriteLine($"Thread 3 is {Thread.CurrentThread.ManagedThreadId}");

            //Task.Run会开启新的线程，加await关键字表示方法后面的内容等待此任务完成再执行
            await Task.Run(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine($"Thread 4 is {Thread.CurrentThread.ManagedThreadId}");
            });

            Console.WriteLine($"Thread 5 is {Thread.CurrentThread.ManagedThreadId}");
            Console.WriteLine("end send message");
        }
    }
}
